package com.example.hydrogengenerator.ui.frag

import android.os.Bundle
import com.example.hydrogengenerator.R
import com.example.hydrogengenerator.base.BaseFragment
import com.example.hydrogengenerator.databinding.FragSettingPasswordBinding
import com.example.hydrogengenerator.model.PasswordModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction

/**
 * @description
 * @author csw
 * @date 2022-11-05
 */
class SettingPasswordFrag:BaseFragment<PasswordModel,FragSettingPasswordBinding>() {
    /**
     * 当前Fragment绑定的视图布局
     */
    override fun layoutId(): Int = R.layout.frag_setting_password

    private var lastBack = false

    private var numberIndex = 0

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.keybordView.onNumberInputListener = ::onNumberInput
    }


    /**
     * 处理键盘事件
     * */
    private fun onNumberInput(text: String, back: Boolean) = with(mDatabind) {
        when {
            lastBack && !back && tvNum1.text.isNotEmpty() -> {
                numberIndex++
            }
            back && !lastBack && tvNum4.text.isEmpty() -> {
                numberIndex--
            }
            else -> {}
        }

        when (numberIndex) {
            0 -> tvNum1
            1 -> tvNum2
            2 -> tvNum3
            else -> tvNum4
        }.also {
            it.text = text
            lastBack = if (back) {
                numberIndex--
                true
            } else {
                numberIndex++
                false
            }
        }
        numberIndex = numberIndex.coerceAtMost(3)
        numberIndex = numberIndex.coerceAtLeast(0)
        if (numberIndex == 3)
            goSetting()
    }

    private fun goSetting() {
        nav().navigateAction(R.id.settingFrag)
    }
}